package com.example.administrator.thread_test;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;

public class ImageActivity extends Activity {
    ImageSwitcher imageSwitcher;
    private int index=0; //图片序号
    private int[ ] images;//存放图片id

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 123) {
                imageSwitcher.setImageResource(images[msg.arg1]);
//设置淡入和淡出动画（见前页，略）
//                imageSwitcher.setImageResource(images[1]); //必须放在工厂后面，否则空指针错
//设置动画：如淡入和淡出
                imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(ImageActivity.this, android.R.anim.fade_in));
                imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(ImageActivity.this, android.R.anim.fade_out));
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image);

        imageSwitcher=(ImageSwitcher) findViewById(R.id.imageSwitcher);
        imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() { //设置工厂
            @Override
            public View makeView() { //重写makeView
                ImageView imageView=new ImageView(ImageActivity.this);
                imageView.setBackgroundColor(0xFFFFFFFF); //白色背景
                imageView.setScaleType(ImageView.ScaleType.CENTER); //居中显示
                imageView.setLayoutParams(new ImageSwitcher.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT) ); //定义布局
                return imageView;
            }
        });
        images = new int[]{
                R.drawable.img1,
                R.drawable.img2,
                R.drawable.img4
        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (index < images.length) {
                    Message msg = new Message();
                    msg.what = 123;
                    msg.arg1 = index;
                    handler.sendMessage(msg);
                    index++;
                    if (index == images.length) {
                        index = 0;
                    }
                    try {
                        Thread.sleep(2000); //暂停2秒继续，try…catch省略
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();


    }
}
